package org.smart4j.framework.proxy;

import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.annotation.Transaction;
import org.smart4j.framework.helper.DatabaseHelper;

/**
 * description: 事务代理管理
 * @version v1.0
 * @author w
 * @date 2018年10月20日下午10:23:37
 **/
public class TransactionProxy implements Proxy {
	
	
	private static final Logger logger = LoggerFactory.getLogger(TransactionProxy.class);
	
	/**
	 * 保证同一线程中事务逻辑开关只会执行一次。
	 */
	private static final ThreadLocal<Boolean> FLAG_HOLDER = new ThreadLocal<Boolean>(){
		@Override
		protected Boolean initialValue() {
			return false;
		};
	};
	
	
	@Override
	public Object doProxy(ProxyChain proxyChain) throws Throwable {
		Object result;
		Boolean flag = FLAG_HOLDER.get();
		Method targetMethod = proxyChain.getTargetMethod();
		if(!flag && targetMethod.isAnnotationPresent(Transaction.class)){
			try {
				DatabaseHelper.beginTransaction();
				logger.debug("begin transaction ");
				
				result = proxyChain.doProxyChain();
				
				DatabaseHelper.commitTransaction();
				logger.debug("commit transaction ");
			} catch (Exception e) {
				DatabaseHelper.rollBackTransaction();
				logger.error("rollback transaction ");
				throw e;
			}finally{
				FLAG_HOLDER.remove();
			}
		}else{
			result = proxyChain.doProxyChain();
		}
		return result;
	}

}
